//
//  UserAccountVC.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/6/19.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "UserAccountVC.h"
#import "HeaderView.h"
#import "PointHistory.h"
#import "HistoryItemCell.h"

@interface UserAccountVC () <UITableViewDelegate, UITableViewDataSource> {
    BOOL isShow;
    BOOL isShowAccount;
    int mStart;
}

@property(weak, nonatomic) IBOutlet UIButton *backBt;
@property(weak, nonatomic) IBOutlet UIButton *questionBt;
@property(weak, nonatomic) IBOutlet UITableView *tableView;

@property(strong, nonatomic) HeaderView *headerView;
@property(strong, nonatomic) NSMutableArray *dataSource;
@end

@implementation UserAccountVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestData];
    [self requestList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView {
    self.dataSource = [[NSMutableArray alloc] init];
    void (^block) (void) = ^ {
        NSString *msg = @"\n1、开启Accel加速链挖矿后，您可以通过分享闲置带宽、存储空间及计算资源来获取积分。\n2、昨日获得的积分于每日凌晨2:00更新，积分将自动存入你的账户余额中。\n3、绑定钱包后，所有设备收益将自动转入绑定的钱包地址，但账户余额不会自动转入。\n";
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"挖矿活动说明" message:msg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [vc addAction:cancel];
        [self setUIAlertController:vc MessageAlign:NSTextAlignmentJustified];
        [self presentViewController:vc animated:YES completion:nil];
    };
    [[self.backBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [[self.questionBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        block();
    }];
    float width = [UIScreen mainScreen].bounds.size.width-32;
    float height = width*8/15+60+40+10;
    self.headerView = [[[NSBundle mainBundle] loadNibNamed:@"HeaderView" owner:self options:nil] objectAtIndex:0];
    [self.headerView setFrame:CGRectMake(0, 0, width, height)];
    [self.headerView setBackgroundColor:[UIColor clearColor]];
    UIView *viewWrapper = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    [viewWrapper addSubview:self.headerView];
    self.tableView.tableHeaderView = viewWrapper;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"HistoryItemCell" bundle:nil] forCellReuseIdentifier:@"HistoryItemCellID"];
    self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        [self requestList];
    }];
    self.headerView.unbindView.layer.cornerRadius = 14;
    self.headerView.extractView.layer.cornerRadius = globalRadius;
    self.headerView.walletView.layer.cornerRadius = globalRadius;
    [[self.headerView.topBindBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"User" bundle:nil];
        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"WalletBindVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [[self.headerView.unbindBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"User" bundle:nil];
        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"WalletUnbindVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [[self.headerView.extractBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"User" bundle:nil];
        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"WalletExtractVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [[self.headerView.walletBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"User" bundle:nil];
        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"WalletBindVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [[self.headerView.operateBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        NSString *address = getValueByKey(@"ss_wallet_address");
        if (address) {
            self->isShowAccount = !self->isShowAccount;
            if (self->isShowAccount) {
                [self.headerView.addressBt setImage:[UIImage imageNamed:@"img_open"] forState:UIControlStateNormal];
                self.headerView.addressLb.text = address;
            } else {
                [self.headerView.addressBt setImage:[UIImage imageNamed:@"img_close"] forState:UIControlStateNormal];
                address = [address substringFromIndex:address.length-4];
                [self.headerView.addressLb setText:[NSString stringWithFormat:@"**** **** **** **** **** **** **** **** %@", address]];
            }
        }
    }];
}

- (void)requestData {
    //钱包地址
    [[[HttpRequest shareInstance] signGet:s_wallet  map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            @try {
                id data = x[@"data"];
                if (data) {
                    saveValueByKey(data, @"ss_wallet_address");
                } else {
                    removeValueByKey(@"ss_wallet_address");
                }
                [self updateCard];
            } @catch (NSException *exception) {
                
            }
        } else if ([x[@"code"] intValue] == 1005) {
            removeValueByKey(@"ss_wallet_address");
            [self updateCard];
        }
    } ];
    //账户余额
    [[[HttpRequest shareInstance] signGet:w_point map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            @try {
                id data = x[@"data"];
                if (data[@"point"]) {
                    saveValueByKey(data[@"point"], @"ss_point");
                    [self updateBalance];
                }
            } @catch (NSException *exception) {
                
            }
        }
    }];
}

- (void)requestList {
    [self showLoading:@"加载中"];
    NSDictionary *dic = @{@"start": [NSNumber numberWithInteger:mStart], @"length": [NSNumber numberWithInt:mLength]};
    [[[HttpRequest shareInstance] signGet:w_point_history map:[NSMutableDictionary dictionaryWithDictionary:dic]] subscribeNext:^(id x) {
        [self hideLoading];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([x[@"code"] intValue] == 200) {
            NSError *error;
            NSArray *temp = [MTLJSONAdapter modelsOfClass:[PointHistory class] fromJSONArray:x[@"data"] error:&error];
            if (!error) {
                if (self->mStart == 0) {
                    [self.dataSource removeAllObjects];
                }
                if (self.dataSource.count<mLength) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
                [self.dataSource addObjectsFromArray:temp];
                [self.tableView reloadData];
            } else {
                [JPToast showText:@"数据解析错误"];
            }
        } else {
            [JPToast showText:x[@"message"]];
        }
    } error:^(NSError *error) {
        [self hideLoading];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [JPToast showText:@"网络错误"];
    }];
}

- (void)updateCard {
    NSString *address = getValueByKey(@"ss_wallet_address");
    if (!address) {
        self.headerView.accountLb.text = @"账户余额 (未绑定)";
        self.headerView.walletLb.text = @"绑定钱包地址";
        self.headerView.addressView.hidden = YES;
        self.headerView.unbindView.hidden = YES;
        [self.headerView.bgIv setImage:[UIImage imageNamed:@"img_unbind"]];
//        self.headerView.accountLb.textColor = colorWithString(@"#000000");
//        self.headerView.balanceLb.textColor = colorWithString(@"#000000");
        self.headerView.topBindBt.hidden = NO;
    } else {
        self.headerView.accountLb.text = @"账户余额 (已绑定)";
        self.headerView.walletLb.text = @"修改钱包地址";
        self.headerView.addressView.hidden = NO;
        self.headerView.unbindView.hidden = NO;
        address = [address substringFromIndex:address.length-4];
        [self.headerView.addressLb setText:[NSString stringWithFormat:@"****  ****  ****  ****  %@", address]];
        [self.headerView.bgIv setImage:[UIImage imageNamed:@"ACCEL"]];
//        self.headerView.accountLb.textColor = colorWithString(@"#ffffff");
//        self.headerView.balanceLb.textColor = colorWithString(@"#ffffff");
        self.headerView.topBindBt.hidden = YES;
    }
}

- (void)updateBalance {
    double point = 0.0;
    id data = getValueByKey(@"ss_point");
    if (data) {
        @try {
            point = [data doubleValue];
        } @catch (NSException *exception) {
            
        }
    }
    NSString *text = [[NSNumber numberWithDouble:point] stringValue];
    if (point == 0) {
        text = [[NSNumber numberWithDouble:point] stringValue];
    }
    self.headerView.balanceLb.attributedText = [self handleBigSmallText:text];
}

#pragma mark UITableView delegate and datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 40;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)];
//    [lb setText:@"账户收支明细"];
//    [lb setTextColor:colorWithString(@"2dff9e")];
//    return lb;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (0<= indexPath.row && indexPath.row<self.dataSource.count) {
        PointHistory *model = self.dataSource[indexPath.row];
        if ([model.deltaType intValue] != 1 && model.businessId && model.businessId.length>0) {
            return 82;
        } else {
            return 80;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HistoryItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryItemCellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell performSelector:@selector(setModel:) withObject:self.dataSource[indexPath.row]];
    return cell;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
